package com.xbongbong.saas.service.impl;

import com.alibaba.dingtalk.openapi.exception.OApiException;
import com.alibaba.dingtalk.openapi.helper.Env;
import com.alibaba.dingtalk.openapi.helper.GroupRobotHelper;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.URLEncodeUtils;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.saas.domain.entity.DingBundleUserEntity;
import com.xbongbong.saas.domain.entity.DingRobotManageEntity;
import com.xbongbong.saas.enums.DingtalkPageUrlEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.mini.DingBundleRobotMsgKeyEnum;
import com.xbongbong.saas.enums.mini.DingRobotManagePushEnum;
import com.xbongbong.saas.model.DingBundleUserModel;
import com.xbongbong.saas.model.DingRobotManageModel;
import com.xbongbong.saas.service.DingRobotService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 逍邦网络科技有限公司<p>
 *
 * @author chenshan
 * @version v1.0
 * @since 2020/9/1 9:13 下午
 */
@Service("dingRobotService")
public class DingRobotServiceImpl implements DingRobotService {
    private static final Logger LOG = LoggerFactory.getLogger(DingRobotServiceImpl.class);
    @Resource
    private GroupRobotHelper groupRobotHelper;
    @Resource
    private DingBundleUserModel dingBundleUserModel;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private DingRobotManageModel dingRobotManageModel;
    
    @Override
    public void sendRobotByBusinessType(String corpid, String userId, String userName, PaasFormDataEntity paasFormDataEntity, XbbRefTypeEnum businessTypeEnum) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("userId", userId);
        param.put("del", 0);
        List<DingBundleUserEntity> dingBundleUserList = dingBundleUserModel.findEntitys(param);
        if ( CollectionsUtil.isEmpty(dingBundleUserList) ) {
            return;
        }
        userName = dingBundleUserList.get(0).getName();
        List<String> openConversationIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        dingBundleUserList.forEach(dingBundleUserEntity -> {
            openConversationIdIn.add(dingBundleUserEntity.getOpenConversationId());
        });
        if ( !openConversationIdIn.isEmpty() ) {
            param.clear();
            param.put("openConversationIdIn",openConversationIdIn);
            List<DingRobotManageEntity> dingRobotManageList = null;
            JSONObject data = paasFormDataEntity.getData();
            String text = null;
            String messageUrl = proBaseConfig.getPushFrontUrl() + "index.html?corpid=" + corpid + "&appid=" + Env.DING_XBB_APP_ID + "&dd_nav_bgcolor=ffff943e#";
            String pcMessageUrl = "dingtalk://dingtalkclient/page/link?url=";
            switch (businessTypeEnum) {
                case CONTRACT:
                    param.put("alias",DingRobotManagePushEnum.CLINCH_DEAL_CONTRACT.getAlias());
                    dingRobotManageList = dingRobotManageModel.findEntitys(param);
                    dingRobotManageList.forEach(entity ->{
                        if (Objects.equals(entity.getEnable(),0)){
                            openConversationIdIn.remove(entity.getOpenConversationId());
                        }
                    });
                    if ( CollectionsUtil.isEmpty(openConversationIdIn) ) {
                        return;
                    }
                    Double amount = data.getDoubleValue(ContractEnum.AMOUNT.getAttr());
                    DecimalFormat df = new DecimalFormat("###############0.00");
                    String amountStr = df.format(amount);
                    if ( amountStr.length() > 0 ) {
                        text = "[%s]新签了一份%s元的合同订单。";
                        text = String.format(text, userName, amountStr);
                        messageUrl += String.format(DingtalkPageUrlEnum.CONTRACT_DETAIL.getUrl(), paasFormDataEntity.getId(), paasFormDataEntity.getAppId(), paasFormDataEntity.getMenuId(), paasFormDataEntity.getFormId());
                    }
                    break;
                case COMMUNICATE_PLAN:
                    param.put("alias",DingRobotManagePushEnum.VISITORS_TO_PLAN.getAlias());
                    dingRobotManageList = dingRobotManageModel.findEntitys(param);
                    dingRobotManageList.forEach(dingRobotManageEntity -> {
                        if (Objects.equals(dingRobotManageEntity.getEnable(), 0)) {
                            openConversationIdIn.remove(dingRobotManageEntity.getOpenConversationId());
                        }
                    });
                    if ( CollectionsUtil.isEmpty(openConversationIdIn) ) {
                        return;
                    }
                    text = "[%s]刚刚创建了一个访客计划。";
                    text = String.format(text, userName);
                    messageUrl += String.format(DingtalkPageUrlEnum.COMMUNICATE_PLAN_DETAIL.getUrl(), paasFormDataEntity.getId(), paasFormDataEntity.getAppId(), paasFormDataEntity.getMenuId(), paasFormDataEntity.getFormId());
                    break;
                default:
                    break;
            }
            pcMessageUrl += URLEncodeUtils.encodeURL(messageUrl) + "&pc_slide=true";
            groupRobotHelper.sendRobotMsg(DingBundleRobotMsgKeyEnum.ACTIONCARD_1, corpid, userName, null, openConversationIdIn, text,pcMessageUrl);
        }
    }
}
